import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'dart:math';

import '../../common/index.dart';
import 'index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});

  // 欢迎标题
  Widget _build_welcome() {
    return FadeTransition(
      opacity: controller.fade_animation,
      child: SizedBox(
        height: 140.h,
        width: double.infinity,
        child: Stack(
          children: [
            Positioned(
              left: 16.w,
              child: Text(
                'Welcome',
                style: TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w900,
                  color: Colors.white,
                  fontFamily: "Arial",
                ),
              ),
            ),
            Positioned(
              top: 48.h,
              left: 16.w,
              child: SizedBox(
                child: Row(
                  children: [
                    SizedBox(
                      width: 125.w,
                      child: Text(
                        controller.user?.name ?? "You",
                        style: TextStyle(
                          fontSize: 40.sp,
                          fontWeight: FontWeight.w900,
                          color: Color(0xffCDFE64),
                          fontFamily: "Arial",
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    AnimatedBuilder(
                      animation: controller.pulse_animation,
                      builder: (context, child) {
                        return Transform.scale(
                          scale: controller.pulse_animation.value,
                          child: Image.asset(
                            'assets/images/home_background.png',
                            width: 82.w,
                            height: 82.h,
                          ),
                        );
                      },
                    ),
                  ],
                ).paddingOnly(top: 10.h),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建帖子展示组件
  Widget _build_square() {
    return FadeTransition(
      opacity: controller.fade_animation,
      child: SlideTransition(
        position: controller.slide_animation,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          padding: EdgeInsets.all(15.r),
          decoration: BoxDecoration(
            color: Color(0xFFCDFF5F),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Square',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w900,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      controller.play_button_animation();
                      RouteUtil.push(RouteNames.community);
                    },
                    child: AnimatedBuilder(
                      animation: controller.shake_controller,
                      builder: (context, child) {
                        return Transform.scale(
                          scale: controller.button_scale_animation.value,
                          child: SvgPicture.asset(
                            AssetsImages.go,
                            width: 33.w,
                            height: 33.h,
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
              SizedBox(height: 15.h),
              SizedBox(
                width: double.infinity,
                height: 150.h,
                child: FutureBuilder<List<PostModel>>(
                  future: controller.load_posts(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return Center(child: CircularProgressIndicator());
                    }
                    if (!snapshot.hasData || snapshot.data!.isEmpty) {
                      return Center(child: Text('No posts available'));
                    }

                    return PageView.builder(
                      controller: PageController(
                        viewportFraction: 0.85,
                        initialPage: 0,
                      ),
                      physics: ClampingScrollPhysics(),
                      padEnds: false,
                      itemCount: snapshot.data!.length,
                      itemBuilder: (context, index) {
                        final post = snapshot.data![index];
                        return _buildPostCard(post);
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建帖子卡片
  Widget _buildPostCard(PostModel post) {
    final user = UserService().get_user_data_by_id(post.user_id);
    final String avatarPath = user?.avatar_image ?? AssetsImages.avatar;
    final String userName = user?.name ?? 'Unknown';
    final imagePathHandler = ImagePath();

    return GestureDetector(
      onTap: () {
        HapticFeedback.lightImpact();
        RouteUtil.push(RouteNames.postDetail, extra: post);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 5.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15.r),
        ),
        clipBehavior: Clip.antiAlias,
        child: Stack(
          children: [
            // 帖子图片
            Positioned.fill(
              child: FutureBuilder<List<String>>(
                future: ImagePath.process_post_image_list(post.post_image_list),
                builder: (context, snapshot) {
                  if (!snapshot.hasData || snapshot.data!.isEmpty) {
                    return Image.asset(
                      'assets/images/default_post.png',
                      fit: BoxFit.cover,
                      width: 200.w,
                      height: 140.h,
                    );
                  }

                  final firstImagePath = snapshot.data!.first;
                  return Image(
                    image: imagePathHandler.get_post_image(firstImagePath),
                    fit: BoxFit.cover,
                    width: 200.w,
                    height: 140.h,
                  );
                },
              ),
            ),
            // 底部用户信息（只在左下角）
            Positioned(
              left: 10.w,
              bottom: 10.h,
              child: Row(
                children: [
                  // 用户头像
                  Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 2),
                      image: DecorationImage(
                        image: ImagePath().get_avatar_image(avatarPath),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  // 用户名
                  Text(
                    userName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.bold,
                      shadows: [
                        Shadow(
                          offset: Offset(1, 1),
                          blurRadius: 3,
                          color: Colors.black.withOpacity(0.5),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建灌溉日历组件
  Widget _build_calendar() {
    final now = DateTime.now();
    final first_day = DateTime(now.year, now.month - 3, 1);
    final last_day = DateTime(now.year, now.month + 3, 0);

    return GetBuilder<HomeController>(
      id: "calendar",
      builder: (controller) {
        return FadeTransition(
          opacity: controller.fade_animation,
          child: SlideTransition(
            position: controller.slide_animation,
            child: Container(
              margin: EdgeInsets.all(20.r),
              padding: EdgeInsets.all(15.r),
              decoration: BoxDecoration(
                color: Color(0xFFCDFF5F),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Column(
                children: [
                  // 日历标题
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Irrigation Calendar',
                        style: TextStyle(
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w900,
                          color: Colors.black,
                          fontFamily: "Arial",
                        ),
                      ),
                    ],
                  ),
                  // 日历主体
                  AnimatedBuilder(
                    animation: controller.pulse_animation,
                    builder: (context, child) {
                      return Transform.scale(
                        scale: controller.pulse_animation.value,
                        child: TableCalendar(
                          availableGestures: AvailableGestures.horizontalSwipe,
                          firstDay: first_day,
                          lastDay: last_day,
                          focusedDay: controller.focused_day,
                          currentDay: now,
                          selectedDayPredicate: (day) =>
                              isSameDay(controller.selected_day, day),
                          onDaySelected: (selectedDay, focusedDay) {
                            controller.updateSelectedDay(
                              selectedDay,
                              focusedDay,
                            );
                          },
                          calendarFormat: CalendarFormat.month,
                          headerVisible: true,
                          availableCalendarFormats: const {
                            CalendarFormat.month: 'Month',
                          },
                          onHeaderTapped: (date) {
                            controller.play_pulse_animation();
                          },
                          // 标题格式化
                          headerStyle: HeaderStyle(
                            formatButtonVisible: false,
                            titleCentered: true,
                            leftChevronIcon: SvgPicture.asset(
                              AssetsImages.left,
                              width: 18.w,
                              height: 18.h,
                            ),
                            rightChevronIcon: SvgPicture.asset(
                              AssetsImages.right,
                              width: 18.w,
                              height: 18.h,
                            ),
                            titleTextStyle: TextStyle(
                              color: Colors.black,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w700,
                              fontFamily: "Arial",
                            ),
                            headerPadding: EdgeInsets.symmetric(vertical: 10.r),
                            headerMargin: EdgeInsets.only(bottom: 8.r),
                            titleTextFormatter: (date, locale) =>
                                '${date.year}-${date.month}-${date.day}',
                          ),
                          calendarBuilders: CalendarBuilders(
                            // 自定义选中日期的显示
                            selectedBuilder: (context, date, _) {
                              return Center(
                                child: Container(
                                  width: 35.w,
                                  height: 35.h,
                                  decoration: BoxDecoration(
                                    color: Colors.black,
                                    shape: BoxShape.circle,
                                  ),
                                  child: Center(
                                    child: SvgPicture.asset(
                                      AssetsImages.water,
                                      width: 20.w,
                                      height: 20.h,
                                      colorFilter: ColorFilter.mode(
                                        Colors.white,
                                        BlendMode.srcIn,
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            },
                            headerTitleBuilder: (context, day) {
                              return Center(
                                child: Text(
                                  '${day.year}-${day.month}-${day.day}',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w700,
                                    fontFamily: "Arial",
                                  ),
                                ),
                              );
                            },
                          ),
                          // 日历整体样式配置
                          calendarStyle: CalendarStyle(
                            todayDecoration: BoxDecoration(
                              color: Colors.white,
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: Colors.white,
                                width: 2.r,
                              ),
                            ),
                            todayTextStyle: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.w700,
                              fontFamily: "Arial",
                            ),
                            selectedDecoration: BoxDecoration(
                              color: Colors.black,
                              shape: BoxShape.circle,
                            ),
                            defaultTextStyle: TextStyle(color: Colors.black),
                            weekendTextStyle: TextStyle(color: Colors.black),
                            outsideTextStyle: TextStyle(
                              color: Colors.black.withOpacity(0.5),
                            ),
                            cellMargin: EdgeInsets.all(2.r),
                            cellPadding: EdgeInsets.zero,
                          ),
                          daysOfWeekStyle: DaysOfWeekStyle(
                            weekdayStyle: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                            ),
                            weekendStyle: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                  SizedBox(height: 10.h),
                  // 浇水按钮和水滴动画
                  Stack(
                    children: [
                      // 浇水按钮
                      SizedBox(
                        width: double.infinity,
                        child: AnimatedBuilder(
                          animation: controller.shake_controller,
                          builder: (context, child) {
                            // 计算震动偏移
                            final progress = controller.shake_controller.value;
                            final amplitude = 10.0;
                            final offset =
                                sin(progress * 8 * 3.14159) *
                                amplitude *
                                (1 - progress);

                            return Transform.translate(
                              offset: Offset(offset, 0),
                              child: Transform.scale(
                                scale: controller.button_scale_animation.value,
                                child: ElevatedButton(
                                  onPressed: () {
                                    controller.handle_watering();
                                  },
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: controller.is_watered_today
                                        ? Colors.black
                                        : Colors.black,
                                    disabledBackgroundColor: Colors.black,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(52.r),
                                    ),
                                    padding: EdgeInsets.symmetric(
                                      vertical: 15.r,
                                    ),
                                  ),
                                  child: Center(
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                          if (controller.is_watered_today)
                                          Icon(
                                            Icons.check,
                                            color: Colors.white,
                                            size: 22.sp,
                                          ),
                                        Obx(
                                          () => Text(
                                            controller.isWatering.value
                                                ? 'Watering...'
                                                : (controller.is_watered_today
                                                      ? 'Watered already'
                                                      : 'Watering'),
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16.sp,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),

                      // 水滴动画
                      GetBuilder<HomeController>(
                        id: "water_animation",
                        builder: (controller) {
                          return Visibility(
                            visible: controller.show_water_drop,
                            child: Positioned.fill(
                              child: Center(
                                child: AnimatedBuilder(
                                  animation: controller.water_controller,
                                  builder: (context, child) {
                                    return Transform.scale(
                                      scale:
                                          controller.water_scale_animation.value,
                                      child: SvgPicture.asset(
                                        AssetsImages.water,
                                        width: 50.w,
                                        height: 50.h,
                                        colorFilter: ColorFilter.mode(
                                          Colors.blue.withOpacity(0.7),
                                          BlendMode.srcIn,
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeController>(
      init: HomeController(),
      id: "home",
      builder: (_) {
        return Scaffold(
          extendBody: true,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.bg),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              bottom: false,
              top: true,
              child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 25.h),
                    _build_welcome(),
                    _build_square(),
                    _build_calendar(),
                    SizedBox(height: 80.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
